package FlashServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class PolicyServer extends Thread {
	private int _port;
	private boolean _listening;
	private ServerSocket _socketServer;

	public PolicyServer(int port_, String[] allowedHosts_) 
	{
		_port = port_;
		_listening = true;
		if (allowedHosts_ == null)
			allowedHosts_ = MainServer.DEFAULT_POLICY;
		buildPolicy(allowedHosts_);
	}

	public String buildPolicy(String[] allowedHosts_) 
	{
		StringBuffer policyBuffer = new StringBuffer();

		policyBuffer.append("<?xml version=\"1.0\"?><cross-domain-policy>");
		
		for (int i = 0; i < allowedHosts_.length; i++) 
		{
			String[] hostInfo = allowedHosts_[i].split(":");
			String hostname = hostInfo[0];
			String ports;
			if (hostInfo.length > 1)
				ports = hostInfo[1];
			else
				ports = "*";

			policyBuffer.append("<allow-access-from domain=\"" + hostname + "\" to-ports=\"" + ports + "\" />");
		}
		policyBuffer.append("</cross-domain-policy>");

		return policyBuffer.toString();
	}

	public void run() 
	{
		try 
		{
			_listening = true;
			_socketServer = new ServerSocket(_port, 50);
			if (MainServer.DEBUG)
				System.out.println("PolicyServer listening on port " + _port);

			while (_listening) 
			{
				Socket socket = _socketServer.accept();

				try 
				{
					if (MainServer.DEBUG)
						System.out.println("PolicyServer got a connection on port " + _port);
					(new SocketConnection(socket)).start();
				} 
				catch (Exception e) 
				{
					if (MainServer.DEBUG)
						System.out.println("Exception: " + e.getMessage());
				}
				try 
				{
					sleep(1000);
				} 
				catch (InterruptedException e) 
				{
				}
			}
		} 
		catch (IOException e) 
		{
			if (MainServer.DEBUG)
				System.out.println("IO Exception: " + e.getMessage());
		}
	}
}
